package com.wh.blockquene;

/**
 * 
 *  Class Name: TestWaitAndNotify.java
 *  @author wanghao  DateTime 2016年7月26日 上午11:45:05 
 *  @company hongbo
 *  @email 1228675455@qq.com
 *  Description: 如果是锁住studentDao(synchronized(studentDao))的话那么传入的dao如果为同一实例那么代码块会被锁住，如果锁住的是this(synchronized(this))
 *  的话那么thread必须唯一才能确保代码块被锁住
 */
public class TestWaitAndNotify3 {

	public static void main(String[] args) {
		
		StudentDao dao = new StudentDao();
		 Thread t1 = new Thread(new TestThread(dao)); 
		 Thread t2 = new Thread(new TestThread(dao));
		 t1.start();
		 t2.start();
	}
	
	static class StudentDao {
		
		public void addStudent() {
			System.out.println("线程:" + Thread.currentThread().getName() + " 非同步代码块部分");
			synchronized(this) {
				System.out.println("增加开始");
				try {
					System.out.println("线程开始等待！");
					Thread.currentThread().sleep(10000);
					System.out.println("线程等待结束！");
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
				System.out.println("增加结束");
			}
		}
		
		public void deleteStudent() {
				System.out.println("删除开始");
				try {
					Thread.currentThread().sleep(10000);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
				System.out.println("删除结束");
		}
	}
	
	static class TestThread implements Runnable {

		private StudentDao studentDao;
		
		public TestThread(StudentDao studentDao) {
			super();
			this.studentDao = studentDao;
		}

		@Override
		public void run() {
			//锁住studentDao这个对象
			synchronized(studentDao) {
				System.out.println("线程:" + Thread.currentThread().getName() + "Test");
				studentDao.deleteStudent();
			}
		}
		
	}
	
}
